package com.ougy.reshop.test.recognition;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.ougy.reshop.model.Publish;
import com.ougy.reshop.model.User;
import com.ougy.reshop.util.PasswordUtil;

public class PubResultRecognition  extends JsonResultRecognition<List<Publish>>{
	@Override
	public List<Publish> recognition(String result) {
		try {
			JSONTokener jsonTokener = new JSONTokener(result);
			JSONObject obj = (JSONObject) jsonTokener.nextValue();
			boolean hasData = obj.has("data");
			if (!hasData) {
				return null;
			}
			List<Publish> wrapper = new ArrayList<Publish>();
			JSONArray array=(JSONArray)obj.getJSONArray("data");
			for (int i=0; i<array.length(); ++i){
				JSONObject childObj = array.getJSONObject(i);
				Publish entity=new Publish();
				entity.setId(getUuid());
				entity.setTitle(getString(childObj, "title"));
				entity.setDescContent(getString(childObj,"description"));
				entity.setTelPhone(getString(childObj,"contact"));
				entity.setLinkmanName(getString(childObj,"userNick"));
				entity.setViewCount(getInt(childObj, "count"));
				entity.setCreateTime(new Timestamp(getInt(childObj,"createdTime")));
				User user=new User();
				user.setUsername(getString(childObj,"userNick"));
				user.setPassword(PasswordUtil.createPassword(getString(childObj,"userNick")));
				entity.setOwner(user);
				int cityId=getInt(childObj,"areaCityLevelId");
				wrapper.add(entity);
			}
			return wrapper;
		} catch (Exception e) {
			throw new RuntimeException("json parse error" + e);
		}
	}
	
	@Override
	public List<Publish> childRecognition(JSONObject obj) throws Exception {
		return null;
	}
	
	public String getUuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

}
